package com.zhugang.week05;

import java.util.HashMap;
import java.util.Map;

/**
 * @program algorithms
 * @description: singleNumber
 * @author: chanzhugang
 * @create: 2022/07/11 10:58
 */
public class SingleNumber2 {

    public static void main(String[] args) {
        SingleNumber2 singleNumber2 = new SingleNumber2();
        int[] nums = new int[]{4, 1, 2, 1, 2};
        int res = singleNumber2.singleNumber(nums);
        System.out.println(res);
    }

    /**
     * 136 只出现一次的数字
     *
     * @param nums
     * @return
     */
    public int singleNumber(int[] nums) {
        // 遍历数组，元素存入哈希表，查找value值为1的key
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            int count = 1;
            if (map.containsKey(num)) {
                count += map.get(num);
            }
            map.put(num, count);
        }
        for (int num : nums) {
            if (map.get(num) == 1) {
                return num;
            }
        }
        return -1;
    }
}